package main

import (
	"context"
	"embed"
	"errors"
	"flag"
	"fx_swift_boss/internal/service"
	"fx_swift_boss/pkg/cache"
	"fx_swift_boss/pkg/config"
	"fx_swift_boss/pkg/db"
	"fx_swift_boss/pkg/global"
	"fx_swift_boss/pkg/logger"
	"fx_swift_boss/pkg/middleware"
	"fx_swift_boss/router"
	"github.com/gin-gonic/gin"
	"github.com/go-co-op/gocron"
	"github.com/spf13/cast"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var (
	logPath = flag.String("log", "./log", "the log path")

	env = flag.String("e", "", "env")
)

//go:embed *.toml
var FS embed.FS

func main() {
	// 初始化配置文件
	flag.Parse()

	// 初始化 nacos
	var data []byte
	if *env == "dev" {
		data, _ = FS.ReadFile("dev.toml")
		config.InitNacos(data)
	} else if *env == "prod" {
		data, _ = FS.ReadFile("prod.toml")
		config.InitNacos(data)
	}

	// 初始化日志
	logger.InitLogger(*logPath)

	// 初始化数据库
	db.InitGorm()

	// 初始化redis
	cache.InitRedis()

	engine := gin.Default()
	engine.Use(middleware.GinCorsHandler())
	router.InitRouter(engine)

	//engine.GET("/ws", func(c *gin.Context) {
	//	notify.WebStockRun(c)
	//})
	//go notify.SendKeepAlive()

	timezone, _ := time.LoadLocation("Asia/Shanghai")
	s := gocron.NewScheduler(timezone)
	s.Every(1).Day().At("01:00").Do(service.NewAgentSrv().ManagementFee, context.Background())

	s.StartAsync()

	srv := &http.Server{
		Addr:         "0.0.0.0:" + cast.ToString(global.ViperObj.GetInt("http.port")),
		Handler:      engine,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
	}
	log.Printf("Listen port start：%s", cast.ToString(global.ViperObj.GetInt("http.port")))
	// 启动服务
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	quit, stop := signal.NotifyContext(context.Background(), syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, os.Interrupt, os.Kill)
	defer stop()
	<-quit.Done()
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Server exiting")
}
